<?php

namespace app\api\logic;

use app\common\library\RedissLock;
use app\common\service\CommonSystemImportService;
use app\data\util\MqQueueName;
use app\purchase\logic\PlanSuggestLogic;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
use DateTime;
class LinXingOrderLogic extends BasicLogic
{
    /**
     * @desc   导入数据处理
     * @author luckyXiong
     * @date   2025-03-19
     */
    public function importInfo($params){
        try{
            $result = CommonSystemImportService::staticModel()->operate_import_data([
                    $this,//当前对应的service
                    'save',//类型: template 下载模板; save :保存 导入
                    CommonSystemImportService::TYPE_IMPORT_LINXING_PAGE,
                    1,
                    $params
                ]
            );
        }catch (\Exception $e) {
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }
    }




    /**
     * @desc 将导入数据写入目标表
     * @author xx
     * @date 2025-03-19
     */
    public function import_order_lin_sku($params=[]){
        $key = 'import_order_lin:'.time();
        $redis_lock = new RedissLock();
        $lock = $redis_lock::lock($key, $redis_lock::UNBLOCK, 300);
        $waybill_no         =   getIsset($params,'waybill_no');
        //数据入库逻辑
        $info = [
            'waybill_no'         => $waybill_no,
        ];

        //update 2025-08-27
        $res = Db::name('checkbill_qqwy')->insertGetId($info);
        $lock->unlock();
        $info['status'] = $res == 1 ? 1:2;
        return  $info;
    }


    /**
     * @param $row
     * @return string[]
     * @desc 数据title 导入组装数据结构
     */
    public function get_excel_row_data($row){
        return [
            'waybill_no'  => empty($row['A'])? '': trim($row['A']),
        ];
    }




    public function get_color($originalString){
        $color = '';
        $size  = '';
        if (preg_match('/-(.*?)-(\w+)/', $originalString, $matches)) {
            // $matches[1] 是颜色，$matches[2] 是尺寸
            $color = trim($matches[1]);
            $size  = trim($matches[2]);
        }

        return [
            'color'=>$color,
            'size' =>$size
        ];
    }


    /**
     * @desc   清洗数据处理
     * @author luckyXiong
     * @date   2025-03-24
     */
    public function change_sku(){
           $where = [];
           $where[] = ['value_1','=',''];
           $list = Db::name('product_lingxin_sku')->field('id,seller_sku,value_1')->where($where)->select()->toArray();
           foreach($list as $v){
               $seller_sku =  $v['seller_sku']??'';
               $info       = self::get_color($seller_sku);
               Db::name('product_lingxin_sku')->where(['id'=>$v['id']])->update(
                   [
                       'value_1'=>$info['size'],
                   ]
               );
           }
        return  $this->jsonMessage(200,true,'操作成功',null);
    }


    public function change_sku_size(){
          $where      = [];
          $where[]    = ['is_seel','=',0];
          $where[]    = ['shop_id','=',17];
          $end        = strtotime(date('Y-m-d', time() - timezone()));
          $start      = strtotime(date('Y-m-d', strtotime('-2 day') - timezone()));
          $where[]    = ['createtime','between', [$start, $end]];
          $field      = 'id,spu,new_sku';
          $list       = Db::name('order_skuinfo')
                       ->field($field)
                       ->where($where)
                       ->select()
                       ->toArray();

          foreach($list as $v){
              //推动数据到队列;
              MqTaskPushLogic::mq_task_push(
                  '',
                  MqQueueName::QUEUE_ORDER_SKU_SIZE_QUEUE,
                  [
                      'spu'         =>$v['spu'],
                      'seller_sku'  =>$v['new_sku'],
                  ],
                  false
              );
          }
    }


    public function change_sku_size_consumer($info){
           $spu          = $info['spu']??'';
           $seller_sku   = $info['seller_sku']??'';
           $product_type = self::get_product_type(['spu'=>$spu]);
           $sizeinfo     = (new PlanSuggestLogic())->get_size($seller_sku,$product_type);
           $data = [
               'spu'        =>$spu,
               'seller_sku' =>$seller_sku,
               'color'      =>$sizeinfo['color']??'',
               'size'       =>$sizeinfo['size'] ?? '',
               'cup'        =>$sizeinfo['cup'] ?? '',
               'create_time'=>date("Y-m-d H:i:s",time()),
           ];
           $exist_info =Db::name('order_sku_size')->where(['spu'=>$spu,'seller_sku'=>$seller_sku])->find();
           if(!$exist_info){
               Db::name('order_sku_size')->insert($data);
           }
           return  true;
    }


    /**
     * @desc   库存导入数据查询是否导入
     * @author luckyXiong
     * @date   2025-06-24
     */
    public function check_product_inventory(){
        $info = Db::name('common_system_import')
                 ->where(['import_type'=>105])
                 ->order('created_unix desc')
                 ->find();
        $created_unix = $info['created_unix']??0;
        $dateTime = new DateTime();
        $currentDate = $dateTime->format("Y-m-d");
        $open_id = Db::name('system_admin')->field('open_id')->where(['id'=>93])->value('open_id');
        if($created_unix){
              $get_date = date("Y-m-d", $created_unix);
              if($get_date!=$currentDate){
                  //发送消息今天没有上传excel或则上传失败;给吕婷发消息
                  $message_info = "今天文件没上传或上传失败!";
                  $datamsg = [
                      'message' => $message_info,
                      'open_id' => $open_id,
                  ];
                  (new FeiShuMessageLogic())->send_message($datamsg);
                  //发送邮件消息通知
                  (new SendEmailLogic())->send_email($message_info);
              }
        }


    }


    /**
     * @desc   根据spu获取产品类型
     * @author luckyXiong
     * @date   2025-06-11
     */
    public function get_product_type($params=[]){
        $spu = $params['spu']??'';
        $res = 5;
        if(preg_match('/^bra/',$spu)){
            $res =1;
        }
        if(preg_match('/^sha/',$spu)){
            $res =2;
        }

        if(preg_match('/^swim/',$spu)){
            $res =3;
        }

        if(preg_match( '/^(pan|paj)/',$spu)){
            $res =4;
        }

        return $res;

    }


    /**
     * @desc   广告名称信息查询
     * @author luckyXiong
     * @date   2025-08-11
     */
    public function get_adv_name($info){

    }










}